package com.xzy.urp.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xzy.urp.mapper.UserInfoMapper;
import com.xzy.urp.pojo.dto.ExcelUserDTO;
import com.xzy.urp.pojo.entity.UserInfo;
import com.xzy.urp.utils.MD5Utils;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@NoArgsConstructor
public class UserExcelListener extends AnalysisEventListener<ExcelUserDTO> {


    private  UserInfoMapper mapper;

    //数据列表
    List<UserInfo> list= new ArrayList<>();

    //数据列表最大值
    private static final int BATCH_COUNT = 10;

    //构造器注入属性
    public UserExcelListener(UserInfoMapper mapper){
        this.mapper = mapper;
    }


    @Override
    public void invoke(ExcelUserDTO data, AnalysisContext context) {

        UserInfo userInfo = new UserInfo();

        String salt = UUID.randomUUID().toString().substring(0, 10);
        userInfo.setUSalt(salt);
        userInfo.setUPassword(MD5Utils.encrypt(data.getPassword(),salt));
        userInfo.setUId(data.getId());
        userInfo.setUType(data.getType());

        list.add(userInfo);



        //将数据表存入数据库
        if (list.size() >= BATCH_COUNT){
            SaveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //当最后剩余数据不足BATCH_COUNT,一次性存储所有数据
        SaveData();
        list.clear();
    }

    private void SaveData(){
        //底层调用保存
        mapper.insertBatch(list);
    }
}
